package multithread.treadLocal.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by xi on 2017/9/17.
 * 测试线程池结合threadlocal的问题
 *
 * 发现：thread2 使用了线程1的数据，共享了线程
 *
 * 原因:线程池把线程提交到队列,当被调用的时候如果存在空闲线程就直接复用线程,仅仅是调用了用户提交的run方法.

 所以当ThreadLocal参数使用完,记得调用remove方法

 除了ThreadLocal 还有 InheritableThreadLocal,子线程可以共享父线程的InheritableThreadLocal

 */
public class TestThreadPool {
    static final ThreadLocal<String> threadParam = new ThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        //固定池内只有存活3个线程
        ExecutorService execService = Executors.newFixedThreadPool(3);
        //死循环几次才能看出效果
        while (true) {
            Thread t = new Thread(()->{
                threadParam.set("abc");
                System.out.println("t1:,threadname:"+Thread.currentThread().getName()+ ",thread value="+threadParam.get());
                //如果不调用remove,将引发问题,后面的线程会享有
               // threadParam.remove();
            });
            execService.execute(t);

            TimeUnit.SECONDS.sleep(1);

            Thread t2 = new Thread(()-> {
                System.out.println("t2,threadname:"+Thread.currentThread().getName()+",thread value=" + threadParam.get());
            });
            execService.execute(t2);
        }
    }

}
